<!--
 * @Author: hu_binbin
 * @Date: 2021-06-15 16:25:52
 * @LastEditTime: 2021-07-30 08:58:28
 * @Description: 选择设备
-->
<template>
  <div class="selectDevice">
    <van-nav-bar title="选择设备" left-text="取消" @click-left="backEvent"   right-text="确认" :border="true" @click-right="confirmEvent" fixed />
    <!-- 加载loading -->
    <van-loading size="24px" class="loading" type="spinner" color="#1989fa" v-if="loading">加载中,请稍后...</van-loading>
    <div v-else class="content">
        <!-- 加载完毕 -->
        <van-search
            v-model.trim="searchkey"
            placeholder="请输入有效关键词查询指定设备"
            @input="onSearch"
            @clear="onCancel"
            />
         <div class="equipmentList">
            <!-- 巡视设备类型列表 -->
            <div v-for="(typeItem,ii) in deviceTypeList" :title="typeItem.bayName" :key="ii" >
                <!-- 父级节点 -->
                <div class="first-cell">
                    <!-- 左侧设备类型及checkbox -->
                    <div class="left-cell">
                        <van-checkbox v-model="typeItem.checked" checked-color="#057b54" 
                        @click="deviceTypeClickEvent(typeItem)">
                            {{typeItem.bayName}} <span>[{{typeItem.deviceList.length}}]</span>
                        </van-checkbox>
                    </div>
                    <!-- 右侧展开合并图标 -->
                    <div class="right-cell" @click="typeItem.isShow = !typeItem.isShow">
                        <van-tag round type="danger">{{ typeItem.result.length }}</van-tag>
                        <van-icon :name="typeItem.isShow ? 'arrow-up':'arrow-down'" />
                    </div>
                </div>
                <!-- 类型下设备列表 -->
                <van-checkbox-group v-model="typeItem.result" v-show="typeItem.isShow">
                    <van-cell v-for="(item,index) in typeItem.deviceList" clickable :key="index"
                    @click="deviceClickEvent(item)">
                        <van-checkbox :name="item.deviceId" checked-color="#057b54" ref="checkboxes">{{ item.deviceName }}</van-checkbox>
                    </van-cell>
                </van-checkbox-group>
            </div>            
        </div>
        <!-- 确定按钮 -->
        <!-- <van-button type="primary" @click="confirmEvent" block class="confirmBtn">确定</van-button> -->
    </div>
  </div>
</template>

<script>
import {getDeviceAndBayForApp} from "../modules/tour/api/common"
//const PinyinEngine = require('pinyin-engine');
export default {
  name: 'SelectDevice',
  props: {
    subId: {
        type: String,
        default: ""
    },
    seldeviceList: {
        type: Array,
        default: function() {
            return [];
        }
    }
  },
  data() {
    return {
      loading: false, //loading状态
      listLoading: false,
      finished: true,
      searchkey: null, //搜索关键字
      deviceTypeList: [], 
      allDeviceList: [], //所有设备   
      userInfo: {},   
      //pinyinEngineByShow: null,
    }
  },
  methods: {
    // 返回事件
    backEvent() {
        this.loading = false
        this.searchkey = null
        this.$emit('close')
    },
    backEvent() {
        this.$emit('close')
    },
    /**
     * @description: 搜索取消操作
     * @param {*}
     * @return {*}
     */    
    onCancel() {
        this.searchkey = null
        this.initDeviceList()
    },
    /**
     * @description: 搜索事件
     * @param {*}
     * @return {*}
     */    
    onSearch() {
        // if (!this.searchkey) {
        //     this.initDeviceList()
        //     return
        // }
        this.initDeviceList()
        var filterArr = [];
        //搜索关键字设备
        this.deviceTypeList.map(item => {
            //子项全部展开显示
            item.isShow = true
            // 从总的设备列表中, 根据当前类型过滤关键字设备
            let devices = item.deviceList.filter(sonItem => {
                //查询是设备名称中是否包含相应字段进行过滤
                if (sonItem.deviceName.includes(this.searchkey)) {
                    return true
                }
            })
            item.deviceList = devices;
            if(item.deviceList.length > 0) {
                filterArr.push(item)
            }
        })
        this.deviceTypeList = filterArr;
    },
    // 确定事件
    confirmEvent() {
        var selectedItem = []
        this.deviceTypeList.map(item => {
            if (item.checked) {
                // 对一级选择项取出
                selectedItem.push(item)
            } else {
                var list = item.deviceList.filter(sonItem => sonItem.checked);
                if(list.length > 0) {
                    var it = JSON.parse(JSON.stringify(item))
                    it.deviceList = list;
                    selectedItem.push(it)
                }
            }            
        })
        if (selectedItem.length == 0) {
            this.$toast.fail('请选择设备')
            return
        }
        this.searchkey = null;
        console.log("selectedItem",selectedItem)
        this.$emit('selDevice', selectedItem)
    },
    /**
     * @description: 父级设备类型点击事件,执行全选与反选
     * @param {*} item 当前点击项
     * @return {*}
     */    
    deviceTypeClickEvent(item) {
        if (item.checked) {
            // 选中后，内部全选
            item.deviceList.map(sonItem => {
                // 内部选中标识
                sonItem.checked = true
                // 展示效果
                item.result.push(sonItem.deviceId)
            })
        } else {
            // 未选中，内部全不选
            item.deviceList.map(sonItem => {
                // 内部选中标识
                sonItem.checked = false;
            })
            // 取消后，清空
            item.result = []
        }
    },
    /**
     * @description: 设备点击事件
     * @param {*} item 当前点击对象
     * @return {*}
     */    
    deviceClickEvent: function(item) {
      //设置当前选择项
      item.checked = !item.checked
      
      //内部全选后，一级设置选中
      this.deviceTypeList.map(devItem => {
          let count = 0
          devItem.deviceList.map(item => {
                if (item.checked) {
                    count++
                }
          })
          //设置上一级选中
          if (count != 0 && count == devItem.deviceList.length) {
              devItem.checked = true
          } else {
              devItem.checked = false
          }
      })            
    },
    /**
     * @description: 初始化设备类型下的设备数据
     * @param {*}
     * @return {*}
     */    
     initDeviceList() {
        // for (var i=0; i < this.deviceTypeList.length; i++) {
        //     var item = this.deviceTypeList[i]
        //     //置空，防止重新初始化时出现多余数据
        //     item.deviceList = []
        //     for (var j =0; j < this.allDeviceList.length; j++) {
        //         var deviceItem = this.allDeviceList[j]
        //         //取得当前间隔下的所有设备
        //         if (item.bayId == deviceItem.bayId) {
        //             console.log("deviceItem===",deviceItem.deviceList)
        //             item.deviceList = deviceItem.deviceList;
        //         }
        //     }
        // }
        this.deviceTypeList = JSON.parse(JSON.stringify(this.allDeviceList));
        this.loading = false
    },
    /**
     * @description: 获取设备列表
     * @param {*}
     * @return {*}
     */
    queryDeviceList() {
        var self = this;
        var params = {
          roleCode: "",
          substationId: this.subId,
          userId: this.userInfo.userId,
		};
        console.log("params",params)
        this.$Toast.loading({
                duration: 0,//展示时长 0不会消失
                message: "正在获取变电站...",
                forbidClick: true,//是否禁止背景点击
                overlay: true//是否显示背景遮罩层
            })
        getDeviceAndBayForApp(params).then(data => {
            self.$Toast.clear();
            if(data.success) {
                self.$Toast.success(data.msg)
                console.log("变电站数据",data.data)
                //var deviceList = data.data;
                var deviceList = self.resetArr(data.data);
                self.deviceTypeList = deviceList.map(item => item);
                //self.pinyinEngineByShow = new PinyinEngine(self.deviceTypeList, ["deviceId","deviceName"])
                self.allDeviceList = JSON.parse(JSON.stringify(deviceList));
                self.dealDevice();
            }else{
                self.$Toast.fail(data.msg)
            }
        }).catch(err => {
            self.$Toast.fail(err)
        })
    },
    /**
     * @description: 重置数组
     * @param {*}
     * @return {*}
     */
    resetArr(deviceList) {
        var deviceType = [];
        deviceList.forEach(item => {
            item['result'] = [];
            item["checked"] = false;
            item["isShow"] = false;
            if(item.deviceList && item.deviceList.length > 0) {
                item.deviceList.forEach(device => {
                    device["checked"] = false;
                    device["bayId"] = item.bayId;
                    device["bayName"] = item.bayName;
                })
                deviceType.push(item);//不显示 间隔下无设备项
            }
        })
        return deviceType
    },
    /**
     * @description: 处理设备选中状态
     * @param {*}
     * @return {*}
     */
    dealDevice() {
        if(this.seldeviceList.length == 0) {
            this.deviceTypeList = this.resetArr(this.deviceTypeList);
            return;
        }
        for(var i  in  this.deviceTypeList) {
            for(var j in this.seldeviceList) {
                //间隔相同时
                if(this.deviceTypeList[i].bayId == this.seldeviceList[j].bayId) {
                    this.deviceTypeList[i].isShow = true;
                    //设备相同全部选中
                    if(this.deviceTypeList[i].deviceList.length == this.seldeviceList[j].deviceList.length){
                        this.deviceTypeList[i].checked = true;
                        //全部选中
                        this.deviceTypeList[i].deviceList.forEach(device => {
                            device.checked = true;
                        })
                        //展示选中数量
                        this.deviceTypeList[i].result = this.deviceTypeList[i].deviceList.map(device => device.deviceId);
                    }else{
                        this.deviceTypeList[i].checked = false;//非全选
                        //全部设备
                        var allDevice = this.deviceTypeList[i].deviceList;
                        this.deviceTypeList[i].result = [];
                        //选中的设备
                        var oldDevice = this.seldeviceList[j].deviceList;
                        for(var k in allDevice) {
                            for(var jj in oldDevice) {
                                if(allDevice[k].deviceId == oldDevice[jj].deviceId) {
                                    allDevice[k].checked = true;
                                    this.deviceTypeList[i].result.push(allDevice[k].deviceId);
                                    break;
                                }
                            }
                        }
                    }
                    break;
                }
            }
        }
    } 
  },
  watch: {
    seldeviceList:{
        handler: function() {
            console.log("=======================")
            this.dealDevice();
        },
        deep:true
    }
  },
  mounted() {
    // 获取巡视指定类型或指定设备列表
    this.loading = false;
  },
  created() {
    var userInfo = localStorage.getItem("userInfo");
	this.userInfo = JSON.parse(userInfo);
    this.queryDeviceList();
  }
}
</script>

<style scoped>
.selectDevice {
    width: 100%;
    height: 100%;
}
.loading {
    top: 30%; 
    text-align:center;
}
.content {    
    height: 85%;
    position: relative;
    top: 47px; 
}
.equipmentList {
    height: 100%;
    overflow-y: auto;
    margin: 10px;
}

.confirmBtn {
    position: fixed;
    bottom: 0;
}
.collapse {
  height: 85%;
  overflow-y: auto;
}

.first-cell {
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    box-sizing: border-box;
    width: 100%;
    padding: 10px 16px;
    overflow: hidden;
    color: #323233;
    font-size: 14px;
    line-height: 24px;
    background-color: #e7f3f0;
}
.left-cell {
    width: 80%;
    cursor: pointer;
}
.right-cell {
    width: 15%;
    text-align: right;
    cursor: pointer;
}
/deep/ .van-nav-bar__title {
  color: #fff !important;
  font-size: 20px !important;
}
/deep/ .van-nav-bar__text, .van-nav-bar .van-icon {
  color: #fff !important;
  font-size: 16px !important;
}
</style>

